package cn.zxw.login;

import cn.zxw.login.entity.BaseEntity;
import cn.zxw.mina.ChatClientSupport;
import cn.zxw.mina.ClientHandler;
import cn.zxw.utils.CommenUtils;
import com.alibaba.fastjson.JSON;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.util.Properties;

//zxw
public class Check {
    public static boolean connect;
    private IoSession session = null;

    public  boolean  checkReturn(String account,String password){
        ChatClientSupport client = new ChatClientSupport();
        Properties properties = CommenUtils.getProperties("plugin.properties");
        String host = properties.get("host").toString();
        String port = properties.get("port").toString();
        connect = client.connect(new NioSocketConnector(), new InetSocketAddress(host, Integer.parseInt(port)));
        if (connect){
            BaseEntity loginEntity = new BaseEntity();
            loginEntity.setSign("login");
            loginEntity.setUsername(account);
            loginEntity.setPassword(password);
            String jsonStr = JSON.toJSONString(loginEntity);
            client.broadcast(jsonStr);
        }
        return connect;
    }

    //获取消息列表
    public  void getMessageList(){
        ChatClientSupport s = ChatClientSupport.chatClientSupport;
        IoSession session = ChatClientSupport.session;
        boolean connected = session.isConnected();
        if (connected){
            BaseEntity listEntity = new BaseEntity();
            listEntity.setSign("notic");
            String token = ClientHandler.token;
            listEntity.setToken(token);
            String jsonStr = JSON.toJSONString(listEntity);
            s.broadcast(jsonStr);
        }
    }

    //退出
    public  void quit(){
        ChatClientSupport s = ChatClientSupport.chatClientSupport;
        BaseEntity loginEntity = new BaseEntity();
        loginEntity.setSign("quit");
        String token = ClientHandler.token;
        loginEntity.setToken(token);
        String jsonStr = JSON.toJSONString(loginEntity);
        s.broadcast(jsonStr);
        s.quit();
    }

}
